package com.gorkr.labuladong.data_struct.bt;

import org.junit.jupiter.api.Test;

import java.util.*;

/**
 * 二叉树的锯齿形层序遍历
 * <p>
 * 层序 加个栈呗
 *
 * @author gorkr
 * @date 2022/07/26 16:01
 **/
public class M103BinaryTreeZigzagLevelOrderTraversal {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {

        List<List<Integer>> res = new LinkedList<>();
        int level = 0;

        Queue<TreeNode> queue = new ArrayDeque<>();
        Stack<Integer> stack = new Stack<>();

        if (root != null) {
            queue.add(root);
        }

        while (!queue.isEmpty()) {
            level++;
            int size = queue.size();

            ArrayList<Integer> item = new ArrayList<>();

            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                if (level % 2 == 1) {
                    item.add(node.val);
                } else {
                    stack.add(node.val);
                }
            }
            while (!stack.isEmpty()) {
                item.add(stack.pop());
            }
            res.add(item);

        }
        return res;

    }

    public List<List<Integer>> zigzagLevelOrder2(TreeNode root) {

        List<List<Integer>> res = new LinkedList<>();
        int level = 0;

        Queue<TreeNode> queue = new ArrayDeque<>();
        Stack<Integer> stack = new Stack<>();

        if (root != null) {
            queue.add(root);
        }

        while (!queue.isEmpty()) {
            level++;
            int size = queue.size();

            ArrayDeque<Integer> deque = new ArrayDeque<>();

            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                if (level % 2 == 1) {

                    deque.offerLast(node.val);
                } else {
                    deque.offerFirst(node.val);
                }

            }
            res.add(new LinkedList<Integer>(deque));
        }
        return res;

    }

}
    